import './_call'
import {ARGS,CALL} from './_cmd'
import {load as footLoad} from './_foot'

split = (msg,pos)=>
  r = []
  p = 0
  for i in pos
    np = p+i
    r.push msg[p...np]
    p = np
  r.push msg[p..]
  return r

do =>
  for k,v of CALL
    if not Array.isArray(v)
      CALL[k] = [v]
  return

export default (msg, remote)->
  [args, body] = footLoad msg
  cmd = args.shift()
  r = ARGS.get cmd
  if r
    [spos, func] = r
    if spos.length
      args = split(body,spos).concat args
    else
      args.unshift body
    args.push remote
    func.apply @, args
    return
  console.log "#{remote.address+":"+remote.port}", msg.length, cmd, msg

  #     {address,port} = remote
  #     nport = msg.readUInt16BE()
  #     console.log address+":"+port, "请求连接，外网测试端口", nport
  #     msg = Buffer.concat [CMD_BIN.PONG, dumpIpv4(address,port)]
  #     @send msg, port, address
  #     @send CMD_BIN.PONG, nport, address
  #   when CMD.PONG
  #     console.log "服务器 #{remote.address+":"+remote.port} 连接成功", "公网地址 "+loadIpv4(msg).join ":"
